package com.wangtao.netty.simple;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.TimeUnit;

public class NettyServerHandler extends ChannelInboundHandlerAdapter{

    EventExecutorGroup group = new DefaultEventExecutorGroup(16);
    //读取事件
    //ChannelHandlerContext上下文对象 含有通道 管道
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("当前线程名称:"+Thread.currentThread().getName());
        //解决方案一 用户程序自定义普通任务
        ctx.channel().eventLoop().execute(()->{
            System.out.println("execute线程名称:"+ Thread.currentThread().getName());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端2..", CharsetUtil.UTF_8));

        });

        group.execute(()->{
            System.out.println("group execute线程名称:"+ Thread.currentThread().getName());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端4..", CharsetUtil.UTF_8));

        });

        //解决方案二 用户自定义定时任务
        ctx.channel().eventLoop().schedule(()->{
            System.out.println("schedule:"+ Thread.currentThread().getName());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端3..", CharsetUtil.UTF_8));

        },1, TimeUnit.SECONDS);

        System.out.println("go on...");

//        System.out.println("服务器读取线程 "+Thread.currentThread().getName());
//        System.out.println("server ctx=" + ctx);
//        System.out.println("看看channel和pipeline的关系");
//        Channel channel = ctx.channel();
//        ChannelPipeline pipeline = ctx.pipeline();
//        //将msg转成ByteBuffer ByteBuf是netty提供的
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println("客户端发送消息是"+buf.toString(CharsetUtil.UTF_8));
//        //buf.toString(CharsetUtil.UTF_8);
//        System.out.println("客户端地址："+ctx.channel().remoteAddress());
    }

    //读取数据完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端1..", CharsetUtil.UTF_8));
    }

    //处理异常,关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
